package com.dangz.dans.interceptor;

import com.alibaba.fastjson.JSON;
import com.dangz.dans.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * HandlerInterceptor 调用方法之前  验证登陆 是否过期
 * @author dangz
 * @since 2017/9/19 18:04
 */
@Component
public class CallIntfaceInterceptor implements HandlerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers",
                "Origin, x-requested-with, authorization,Authorization,Content-Type, Accept");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        //判断是否是同一个调用
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return true;
        }
        String urlString = request.getRequestURI();
        //请求的路径
        //String contextPath = request.getServerName();
        //Integer port = request.getServerPort();
        String encodedAuth = request.getHeader("Authorization");

        if(urlString.indexOf("index") >= 0){
            return true;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

    /**
     * MethonName: exists
     * 判断是否授权接口
     * @params:  [auths, url]
     * @return:  boolean
     *
     * @author: dangz
     * @since: 2017/11/6 14:58
     */
    public boolean exists(List<String> auths, String url) {
        boolean exists = false;
        for (String s : auths) {
            if (s.replace("/","").equals(url.replace("/", ""))) {
                exists = true;
                break;
            }
        }
        return exists;
    }
}
